<template lang="html">
  <el-row class="svg">
     <el-col :span="24" class="marginbottom_10">
        <el-select v-model="companyStr" filterable placeholder="请选择公司" class="inputWidth" @change="selectCompany();"  v-if='userType==0'>
          <el-option v-for="item in companyOptions" :key="item.name" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary"  id="SaveButton" @click="save()">保存</el-button>
        <el-button type="primary" @click="load()"> <i class="tb-control fa fa-eye" ></i>预览</el-button>
    </el-col> 
    <el-col :span="24" >
      <div id="sample">
        <div style="position: relative;width: 100%; display: flex; justify-content: space-between;">
          <div id="myInspectorDiv" class="inspector"> </div>
          <div id="myPaletteDiv" style="width: 110px; margin-right: 2px; background-color: whitesmoke; border: solid 1px black"></div>
          <div id="myDiagramDiv" style="flex-grow: 1; height: 600px; border: solid 1px black"></div>
        </div>
        
        <!--<button id="SaveButton" @click="save()">Save</button>
        -->
        <button @click="load()">Load</button>
        <textarea id="mySavedModel" style="width:100%;height:300px;display:block;">
  { "class": "GraphLinksModel",
  "nodeDataArray": [ 
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"1231231", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-2, "loc":"-495.4999999999999 -219", "angle":90, "size":"8 502.8754486083984"},
{"figure":"LineV", "deviceId":"2131231231313123", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-4, "loc":"-700 -14.937724304199207", "size":"26 404"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"adsadasdasda", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-3, "loc":"-700 -110"},
{"figure":"LogicNot", "deviceId":"asfadfgdfgdg", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-5, "loc":"-650 17.56227569580078", "size":"102 109"},
{"category":"Start", "text":"textNode", "deviceId":"dfgdfgdfg", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-8, "loc":"-600 100"},
{"category":"BYQ", "text":"BYQ", "deviceId":"vccccc", "dataType":"组件", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-1, "loc":"-700 210"},
{"figure":"LineV", "deviceId":"cccccccc", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-7, "loc":"-380 -10", "size":"26 404"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"vvvvvvvv", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-9, "loc":"-380 -110"},
{"figure":"LogicNot", "deviceId":"bbbbbbbbbb", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-10, "loc":"-330 20", "size":"102 109"},
{"category":"Start", "text":"textNode", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-11, "loc":"-280 100"},
{"figure":"LineV", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-13, "loc":"-570 -20", "size":"26 404"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-14, "loc":"-570 -110"},
{"figure":"LogicNot", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-15, "loc":"-520 20", "size":"102 109"},
{"category":"Start", "text":"textNode", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-16, "loc":"-470 100"},
{"category":"textNode", "text":"I(A)", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-18, "loc":"-499.9360046386719 -170.8834129333496"},
{"category":"textNode", "text":"I(A)", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-19, "loc":"-500 -80"},
{"category":"textNode", "text":"I(A)", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-20, "loc":"-500 -110"},
{"category":"textNode", "text":"I(A)", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-21, "loc":"-500 -140"},
{"category":"textNode", "text":"站用变", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-22, "loc":"-698.9949798583984 -250.38341293334963"},
{"category":"textNode", "text":"10KV母线", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-23, "loc":"-380 -250"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-24, "loc":"-260 370", "angle":90, "size":"8 502.8754486083984"},
{"figure":"LineV", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-25, "loc":"-430 570", "size":"26 404"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-26, "loc":"-430 470"},
{"figure":"LogicNot", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-27, "loc":"-380 600", "size":"102 109"},
{"category":"Start", "text":"textNode", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-28, "loc":"-330 680"},
{"category":"BYQ", "text":"BYQ", "deviceId":"", "dataType":"组件", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-29, "loc":"-430 790"},
{"figure":"LineV", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-30, "loc":"-120 570", "size":"26 404"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-31, "loc":"-120 470"},
{"figure":"LogicNot", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-32, "loc":"-70 600", "size":"102 109"},
{"category":"Start", "text":"textNode", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-33, "loc":"-20 680"},
{"category":"BYQ", "text":"BYQ", "deviceId":"", "dataType":"组件", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-34, "loc":"-120 790"},
{"figure":"LineV", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-35, "loc":"-280 570", "size":"26 404"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-36, "loc":"-280 470"},
{"figure":"LogicNot", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-37, "loc":"-230 600", "size":"102 109"},
{"category":"Start", "text":"textNode", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-38, "loc":"-180 680"},
{"category":"BYQ", "text":"BYQ", "deviceId":"", "dataType":"组件", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-39, "loc":"-280 790"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-40, "loc":"300 -230", "angle":90, "size":"8 502.8754486083984"},
{"figure":"LineV", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-41, "loc":"150 -16", "size":"26 412"},
{"text":"", "type":"", "fill":"#52F374", "stroke":null, "deviceId":"", "dataType":"遥信", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-42, "loc":"150 -120"},
{"figure":"LogicNot", "deviceId":"", "dataType":"竖线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-43, "loc":"200 10", "size":"102 109"},
{"figure":"LineH", "deviceId":"", "dataType":"横线", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-6, "loc":"-114.5 190", "size":"532 33.875448608398436"},
{"category":"textNode", "text":"计量柜", "deviceId":"", "dataType":"遥测", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-45, "loc":"250 -80"},
{"text":"asdsad", "figure":"Rectangle", "fill":"#1070C9", "deviceId":"", "dataType":"组件", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-46, "loc":"-560 -250"},
{"category":"switch", "text":"textNode", "deviceId":"", "dataType":"开", "deviceType":"", "deviceName":"", "deviceParam":"", "key":-44, "loc":"250 80"}
 ],
  "linkDataArray": [ {"points":[-570.1500000000003,3.1499999999999773,-570.1500000000003,13.149999999999977,-570.1500000000003,12,-570.1500000000003,12,-570.1500000000003,244,-263.0000000000001,244,-263.0000000000001,362.0000000000002,-263.0000000000001,372.0000000000002]} ]} 
        </textarea>
      
        <button @click="makeSVG()">Render as SVG</button>
        <div id="SVGArea"></div>
      </div>
    </el-col> 
  </el-row>
</template>

<script>
  import '../assets/js/go.js'
  import '../assets/js/mqttws31.min.js'
  import {Inspector} from '../assets/js/DataInspector.js'
  import '../assets/js/cs.js'
  // import {mapGetters, mapActions, mapMutations} from 'vuex'
  // import * as api from "../../api"
  // import * as sysApi from '../../services/sys'
  import $ from 'jquery';
  console.log(Inspector,'Inspector');
  var myDiagram , myPalette;
   export default {
    data(){
      return {
        token:'',
        userType:0,
        inspector:null,
        companyStr:'',
        companyOptions:[],
        deviceTypeArry:[],//设备类型数组
        deviceNameArry:[],//设备数组
        deviceParamArry:[],//设备参数数组
        signalParamArry:[] ,//遥信参数数组
      }
    },
    methods: {
      selectCompany(){
        this.load();
        
      },
      init() {
        if (window.goSamples) goSamples();  // init for these samples -- you don't need to call this
        var objGo = go.GraphObject.make;  // for conciseness in defining templates
        myDiagram =
          objGo(go.Diagram, "myDiagramDiv",  // must name or refer to the DIV HTML element
            {
              grid: objGo(go.Panel, "Grid",
                      objGo(go.Shape, "LineH", { stroke: "#ddd", strokeWidth: 0.5 }),
                      objGo(go.Shape, "LineH", { stroke: "#ddd", strokeWidth: 0.5, interval: 10 }),
                      objGo(go.Shape, "LineV", { stroke: "#ddd", strokeWidth: 0.5 }),
                      objGo(go.Shape, "LineV", { stroke: "#ddd", strokeWidth: 0.5, interval: 10 })
                    ),
              allowDrop: true,  // must be true to accept drops from the Palette
               initialContentAlignment: go.Spot.Center,//自动居中
              // scrollsPageOnFocus:false,
              "toolManager.mouseWheelBehavior": go.ToolManager.WheelZoom,
              // initialAutoScale:go.Diagram.Uniform,
              "draggingTool.dragsLink": true,
              "draggingTool.dragsTree": true,
              "draggingTool.isGridSnapEnabled": true,
              "linkingTool.isUnconnectedLinkValid": true,
              "linkingTool.portGravity": 0,
              "relinkingTool.isUnconnectedLinkValid": true,
              "relinkingTool.portGravity": 0,
              "relinkingTool.fromHandleArchetype":
                objGo(go.Shape, "Diamond", { segmentIndex: 0, cursor: "pointer", desiredSize: new go.Size(8, 8), fill: "tomato", stroke: "darkred" }),
              "relinkingTool.toHandleArchetype":
                objGo(go.Shape, "Diamond", { segmentIndex: -1, cursor: "pointer", desiredSize: new go.Size(8, 8), fill: "darkred", stroke: "tomato" }),
              "linkReshapingTool.handleArchetype":
                objGo(go.Shape, "Diamond", { desiredSize: new go.Size(7, 7), fill: "lightblue", stroke: "deepskyblue" }),
              // rotatingTool: objGo(TopRotatingTool),  // defined below
              "rotatingTool.snapAngleMultiple": 15,
              "rotatingTool.snapAngleEpsilon": 15,
              "undoManager.isEnabled": true
            });
            myDiagram.scrollsPageOnFocus = false;
          function nodeStyle() {
            return [
              // The Node.location comes from the "loc" property of the node data,
              // converted by the Point.parse static method.
              // If the Node.location is changed, it updates the "loc" property of the node data,
              // converting back using the Point.stringify static method.
              new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
              {
                // the Node.location is at the center of each node
                locationSpot: go.Spot.Center,
                resizable: true,
                //isShadowed: true,
                //shadowColor: "#888",
                // handle mouse enter/leave events to show/hide the ports
                mouseEnter: function (e, obj) {
                  that.showPorts(obj.part, true); 
                },
                mouseLeave: function (e, obj) { that.showPorts(obj.part, false); }
              }
            ];
          }
      // when the document is modified, add a "*" to the title and enable the "Save" button
      // myDiagram.addDiagramListener("Modified", function(e) {
      //   var button = document.getElementById("SaveButton");
      //   if (button) button.disabled = !myDiagram.isModified;
      //   var idx = document.title.indexOf("*");
      //   if (myDiagram.isModified) {
      //     if (idx < 0) document.title += "*";
      //   } else {
      //     if (idx >= 0) document.title = document.title.substr(0, idx);
      //   }
      // });

      // Define a function for creating a "port" that is normally transparent.
      // The "name" is used as the GraphObject.portId, the "spot" is used to control how links connect
      // and where the port is positioned on the node, and the boolean "output" and "input" arguments
      // control whether the user can draw links from or to the port.
      function makePort(name, spot, output, input) {
        // the port is basically just a small transparent square
        return objGo(go.Shape, "Circle",
                {
                    fill: null,  // not seen, by default; set to a translucent gray by showSmallPorts, defined below
                    stroke: null,
                    desiredSize: new go.Size(7, 7),
                    alignment: spot,  // align the port on the main Shape
                    alignmentFocus: spot,  // just inside the Shape
                    portId: name,  // declare this object to be a "port"
                    fromSpot: spot, toSpot: spot,  // declare where links may connect at this port
                    fromLinkable: output, toLinkable: input,  // declare whether the user may draw links to/from here
                    cursor: "pointer"  // show a different cursor to indicate potential link point
                });
      }
      var lightText = 'whitesmoke';
      var W_geometry = go.Geometry.parse("M 0,0 L 0,40 M -10,40 L 10,40 10,65 -10,65 -10,40 M 0,67 L 0,77", false);
      myDiagram.nodeTemplateMap.add("Start",
      objGo(go.Node, "Spot", nodeStyle(),
        objGo(go.Panel, "Viewbox",
          objGo(go.Shape, { geometry: W_geometry, stroke: "#52F374",strokeWidth: 2 ,strokeJoin: "bevel", strokeCap: "butt" }),
         
        ),
        makePort("T", go.Spot.Top, true, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, true),
        { // handle mouse enter/leave events to show/hide the ports
          mouseEnter: function(e, node) { showSmallPorts(node, true); },
          mouseLeave: function(e, node) { showSmallPorts(node, false); }
        }
      ));
      var S_geometry = go.Geometry.parse("M 0,0 L 16,0 M 8,0 L 8,10 M 8,10 L 0,30 M 0,45 L 16,45 M 8,45 L 8,30", false);

      myDiagram.nodeTemplateMap.add("switch",
      objGo(go.Node, "Spot", nodeStyle(),
        objGo(go.Panel, "Viewbox",
          objGo(go.Shape, { geometry: S_geometry, stroke: "#52F374",strokeWidth: 2 ,strokeJoin: "bevel", strokeCap: "butt" }),
         
        ),
        makePort("T", go.Spot.Top, true, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, true),
        { // handle mouse enter/leave events to show/hide the ports
          mouseEnter: function(e, node) { showSmallPorts(node, true); },
          mouseLeave: function(e, node) { showSmallPorts(node, false); }
        }
      ));
      var US_geometry = go.Geometry.parse("M 0,0 L 16,0 M 8,0 L 8,5 M 8,14 L 8,30 M 0,45 L 16,45 M 8,45 L 8,30  F M0 0 z M3,10 a5,5 0 1,0 10,0 a5,5 0 1,0 -10,0 z", false);
      // var U_geometry = go.Geometry.parse("F M0 0 z M5,20 a5,5 0 1,0 10,0 a5,5 0 1,0 -10,0 z", false);
      myDiagram.nodeTemplateMap.add("unswitch",
      objGo(go.Node, "Spot", nodeStyle(),
        objGo(go.Panel, "Viewbox",
          // objGo(go.Shape, { geometry: U_geometry, stroke: "#52F374",strokeWidth: 2 ,strokeJoin: "bevel", strokeCap: "butt" }),
          objGo(go.Shape, { geometry: US_geometry, stroke: "#52F374",strokeWidth: 2 ,strokeJoin: "bevel", strokeCap: "butt" }),
        ),
        makePort("T", go.Spot.Top, true, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, true),
        { // handle mouse enter/leave events to show/hide the ports
          mouseEnter: function(e, node) { showSmallPorts(node, true); },
          mouseLeave: function(e, node) { showSmallPorts(node, false); }
        }
      ));
      var xb = require('../assets/img/xb_2.png')
      myDiagram.nodeTemplateMap.add("BYQ",
      objGo(go.Node, "Spot", nodeStyle(),
        objGo(go.Panel, "Auto",
          // objGo(go.Shape, "Circle",
          //   { minSize: new go.Size(40, 40), fill: "#79C900", stroke: null }),
          objGo(go.Picture,{source:xb,width:30,height:55}),
          // objGo(go.TextBlock, "Start",
          //   { font: "bold 11pt Helvetica, Arial, sans-serif", stroke: lightText },
          //   new go.Binding("text"))
        ),
        makePort("T", go.Spot.Top, false, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, true),
        { // handle mouse enter/leave events to show/hide the ports
          mouseEnter: function(e, node) { showSmallPorts(node, true); },
          mouseLeave: function(e, node) { showSmallPorts(node, false); }
        }
      ));
      let device_line = require('../assets/img/device_line.png')
      myDiagram.nodeTemplateMap.add("deviceLine",
      objGo(go.Node, "Spot", nodeStyle(),
        objGo(go.Panel, "Auto",
          // objGo(go.Shape, "Circle",
          //   { minSize: new go.Size(40, 40), fill: "#79C900", stroke: null }),
          objGo(go.Picture,{source:device_line,width:30,height:156}),
          // objGo(go.TextBlock, "Start",
          //   { font: "bold 11pt Helvetica, Arial, sans-serif", stroke: lightText },
          //   new go.Binding("text"))
        ),
        makePort("T", go.Spot.Top, false, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, true),
        { // handle mouse enter/leave events to show/hide the ports
          mouseEnter: function(e, node) { showSmallPorts(node, true); },
          mouseLeave: function(e, node) { showSmallPorts(node, false); }
        }
      ));
      myDiagram.nodeTemplateMap.add("textNode",
      objGo(go.Node, "Spot",{ selectionChanged: this.nodeSelectionChanged }, nodeStyle(),
        objGo(go.Panel, "Auto",
          objGo(go.TextBlock, 
            // { font: "bold 13pt Helvetica, Arial, sans-serif", stroke: lightText , editable: true},
            // new go.Binding("text"))
            // objGo(go.TextBlock,
          {
            font: "bold 13pt Helvetica, Arial, sans-serif",
            margin: 8,
            stroke: lightText,
            maxSize: new go.Size(160, NaN),
            wrap: go.TextBlock.WrapFit,
            editable: true
          },
          new go.Binding("text").makeTwoWay())  //改变text之后导出JSON时会保存起来，否则不会保存起来
        ),
        makePort("T", go.Spot.Top, false, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, true),
        { // handle mouse enter/leave events to show/hide the ports
          mouseEnter: function(e, node) { showSmallPorts(node, true); },
          mouseLeave: function(e, node) { showSmallPorts(node, false); }
        }
      ));
    var nodeSelectionAdornmentTemplate =
      objGo(go.Adornment, "Auto",
        objGo(go.Shape, { fill: null, stroke: "deepskyblue", strokeWidth: 1.5, strokeDashArray: [4, 2] }),
        objGo(go.Placeholder)
      );

    var nodeResizeAdornmentTemplate =
      objGo(go.Adornment, "Spot",
        { locationSpot: go.Spot.Right },
        objGo(go.Placeholder),
        objGo(go.Shape, { alignment: go.Spot.TopLeft, cursor: "nw-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
        objGo(go.Shape, { alignment: go.Spot.Top, cursor: "n-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
        objGo(go.Shape, { alignment: go.Spot.TopRight, cursor: "ne-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),

        objGo(go.Shape, { alignment: go.Spot.Left, cursor: "w-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
        objGo(go.Shape, { alignment: go.Spot.Right, cursor: "e-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),

        objGo(go.Shape, { alignment: go.Spot.BottomLeft, cursor: "se-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
        objGo(go.Shape, { alignment: go.Spot.Bottom, cursor: "s-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" }),
        objGo(go.Shape, { alignment: go.Spot.BottomRight, cursor: "sw-resize", desiredSize: new go.Size(6, 6), fill: "lightblue", stroke: "deepskyblue" })
      );

    var nodeRotateAdornmentTemplate =
      objGo(go.Adornment,
        { locationSpot: go.Spot.Center, locationObjectName: "BpmnActivityLoop" },
        objGo(go.Shape, 'BpmnActivityLoop', { name: "CIRCLE", cursor: "pointer", desiredSize: new go.Size(10, 10),strokeWidth: 1.5, fill: "red", stroke: "deepskyblue" }),
        // { locationSpot: go.Spot.Center, locationObjectName: "CIRCLE" },
        // objGo(go.Shape, "Circle", { name: "CIRCLE", cursor: "pointer", desiredSize: new go.Size(7, 7), fill: "lightblue", stroke: "deepskyblue" }),
        // objGo(go.Shape, { geometryString: "M3.5 7 L3.5 30", isGeometryPositioned: true, stroke: "deepskyblue", strokeWidth: 1.5, strokeDashArray: [4, 2] })
      );
    
    myDiagram.nodeTemplate =
      objGo(go.Node, "Spot",
        { selectionChanged: this.nodeSelectionChanged },
        { locationSpot: go.Spot.Center },
        new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
        { selectable: true, selectionAdornmentTemplate: nodeSelectionAdornmentTemplate },
        { resizable: true, resizeObjectName: "PANEL", resizeAdornmentTemplate: nodeResizeAdornmentTemplate },
        { rotatable: true, rotateAdornmentTemplate: nodeRotateAdornmentTemplate },
        new go.Binding("angle").makeTwoWay(),
        // the main object is a Panel that surrounds a TextBlock with a Shape
        objGo(go.Panel, "Auto",
          { name: "PANEL" },
          new go.Binding("desiredSize", "size", go.Size.parse).makeTwoWay(go.Size.stringify),
          objGo(go.Shape, "Rectangle",  // default figure
            {
              portId: "", // the default port: if no spot on link data, use closest side
              fromLinkable: false, toLinkable: false, cursor: "pointer",
              fill: "white",  // default color
              stroke:'#52F374',
              strokeWidth: 2
            },
            new go.Binding("figure"),   
            new go.Binding("fill")),
          objGo(go.TextBlock,
            {
              font: "bold 11pt Helvetica, Arial, sans-serif",
              margin: 8,
              stroke: "white",
              maxSize: new go.Size(160, NaN),
              wrap: go.TextBlock.WrapFit,
              editable: true
            },
            new go.Binding("text").makeTwoWay())
        ),
        // four small named ports, one on each side:
        makePort("T", go.Spot.Top, false, true),
        makePort("L", go.Spot.Left, true, true),
        makePort("R", go.Spot.Right, true, true),
        makePort("B", go.Spot.Bottom, true, false),
        { // handle mouse enter/leave events to show/hide the ports
          mouseEnter: function(e, node) { showSmallPorts(node, true); },
          mouseLeave: function(e, node) { showSmallPorts(node, false); }
        }
      );

    function showSmallPorts(node, show) {
      node.ports.each(function(port) {
        if (port.portId !== "") {  // don't change the default port, which is the big shape
          port.fill = show ? "rgba(0,0,0,.3)" : null;
        }
      });
    }

    var linkSelectionAdornmentTemplate =
      objGo(go.Adornment, "Link",
        objGo(go.Shape,
          // isPanelMain declares that this Shape shares the Link.geometry
          { isPanelMain: true, fill: null, stroke: "deepskyblue", strokeWidth: 0 })  // use selection object's strokeWidth
      );

    myDiagram.linkTemplate =
      objGo(go.Link,  // the whole link panel
        { selectable: true, selectionAdornmentTemplate: linkSelectionAdornmentTemplate },
        { relinkableFrom: true, relinkableTo: true, reshapable: true },
        {
          routing: go.Link.AvoidsNodes,
          curve: go.Link.JumpOver,
          corner: 5,
          toShortLength: 4
        },
        new go.Binding("points").makeTwoWay(),
        objGo(go.Shape,  // the link path shape
          { isPanelMain: true, strokeWidth: 2 ,stroke: "#52F374" }),
        // objGo(go.Shape,  // the arrowhead
        //   { toArrow: "Standard", stroke: null }),
        objGo(go.Panel, "Auto",
          new go.Binding("visible", "isSelected").ofObject(),
          // objGo(go.Shape, "RoundedRectangle",  // the link shape   //连接线上加文字
          //   { fill: "#F8F8F8", stroke: '#F8F8F8' }),
          objGo(go.TextBlock,
            {
              textAlign: "center",
              font: "10pt helvetica, arial, sans-serif",
              stroke: "#919191",
              margin: 2,
              minSize: new go.Size(10, NaN),
              editable: true
            },
            new go.Binding("text").makeTwoWay())
        )
      );
   // this.load();  // load an initial diagram from some JSON text

    // initialize the Palette that is on the left side of the page
    myPalette =
      objGo(go.Palette, "myPaletteDiv",  // must name or refer to the DIV HTML element
        {
          maxSelectionCount: 1,
          nodeTemplateMap: myDiagram.nodeTemplateMap,  // share the templates used by myDiagram
          linkTemplate: // simplify the link template, just in this Palette
            objGo(go.Link,
              { // because the GridLayout.alignment is Location and the nodes have locationSpot == Spot.Center,
                // to line up the Link in the same manner we have to pretend the Link has the same location spot
                locationSpot: go.Spot.Center,
                selectionAdornmentTemplate:
                  objGo(go.Adornment, "Link",
                    { locationSpot: go.Spot.Center },
                    objGo(go.Shape,
                      { isPanelMain: true, fill: null, stroke: "deepskyblue", strokeWidth: 0 }),
                    objGo(go.Shape,  // the arrowhead
                      { toArrow: "Standard", stroke: 'deepskyblue' })
                  )
              },
              {
                routing: go.Link.AvoidsNodes,
                curve: go.Link.JumpOver,
                corner: 5,
                toShortLength: 4
              },
              new go.Binding("points"),
              objGo(go.Shape,  // the link path shape
                { isPanelMain: true, strokeWidth: 2 ,stroke: '#52F374'}),//绿色
              objGo(go.Shape,  // the arrowhead
                { toArrow: "Standard", stroke: '#52F374',fill:'#52F374' })
            ),
          model: new go.GraphLinksModel([  // specify the contents of the Palette
            { category: "BYQ", text: "BYQ",deviceId:'' ,dataType:'组件', deviceType:'',deviceName:'',deviceParam:''}, 
            { text: "", type:'',fill: "#52F374", stroke: null,deviceId:'',dataType:'遥信', deviceType:'',deviceName:'',deviceParam:'' },
            { category: "deviceLine", text: "deviceLine" ,deviceId:'',dataType:'组件', deviceType:'',deviceName:'',deviceParam:''}, 
            { figure: "LineV" ,deviceId:'',dataType:'竖线', deviceType:'',deviceName:'',deviceParam:''}, 
            { figure: "LogicNot" ,deviceId:'',dataType:'竖线', deviceType:'',deviceName:'',deviceParam:''}, 
            { figure: "LineH" ,deviceId:'',dataType:'横线', deviceType:'',deviceName:'',deviceParam:''}, 
            { category: "textNode", text: "textNode" ,deviceId:'',dataType:'遥测', deviceType:'',deviceName:'',deviceParam:''},
            { category: "Start", text: "textNode" ,deviceId:'',dataType:'遥测', deviceType:'',deviceName:'',deviceParam:''},
            { category: "switch", text: "textNode" ,deviceId:'',dataType:'开', deviceType:'',deviceName:'',deviceParam:''},
            { category: "unswitch", text: "textNode" ,deviceId:'',dataType:'关', deviceType:'',deviceName:'',deviceParam:''},
            { text: "1#HLG01", figure: "Rectangle", fill: "#1070C9",deviceId:'',dataType:'组件', deviceType:'',deviceName:'',deviceParam:''},
          ], [
            // the Palette also has a disconnected Link, which the user can drag-and-drop
            { points: new go.List(go.Point).addAll([new go.Point(0, 0), new go.Point(30, 0), new go.Point(30, 40), new go.Point(60, 40)])},
            { points: new go.List(go.Point).addAll([new go.Point(0, 0), new go.Point(60, 0)])}
          ])
        });
      
      // Show the primary selection's data, or blanks if no Part is selected:
      var that=this;
      var inspector = new Inspector('myInspectorDiv', myDiagram,
        {
          // uncomment this line to only inspect the named properties below instead of all properties on each object:
          // includesOwnProperties: false,
          properties: {
            "text": {show: false  },
            // key would be automatically added for nodes, but we want to declare it read-only also:
            // color would be automatically added for nodes, but we want to declare it a color also:
            "color": { show: Inspector.showIfPresent, type: 'color' },
            // Comments and LinkComments are not in any node or link data (yet), so we add them here:
            "Comments": { show: false  },
            "size": { show: false  },
            "key": { show: false  },
            "loc": { show: false  },
            "category": { show: false  },
            "deviceId": { show: false  },
            "fill": { show: false  },
            "figure": { show: false  },
            "points": { show: false  },
            "stroke": { show: false  },
            "flag": { show:false, type: 'checkbox' },
            // "dataType": {readOnly: true,show: Inspector.showIfNode},
            "dataType": {
              show: Inspector.showIfNode,
              type: "select",
              choices: function(node, propName) {
                if (Array.isArray(node.data.choices)) return node.data.choices;
                return ['遥测','遥脉','组件','遥信'];
              }
            },
            "deviceType": {
              show:false,
              type: "select",
              choices: function(node, propName) {
                if (Array.isArray(node.data.choices)) return node.data.choices;
                return that.deviceTypeArry;
              }
            },
             "type": {
              show:false,
            },
            "deviceName": {
              show: Inspector.showIfNode,
              type: "select",
              choices: function(node, propName) {
                if (Array.isArray(node.data.choices)) return node.data.choices;
                return that.deviceNameArry;
              }
            }, 
           "deviceParam": { //遥测的参数
              show: Inspector.showIfTextNode,
              type: "select",
              choices: function(node, propName) {
                if (Array.isArray(node.data.choices)) return node.data.choices;
                return that.deviceParamArry;
                // return [{id:1,name:'acurrent'},{id:2,name:'cvoltage'}];
              }
            },
            "signalParam":{  //遥信的参数
              show: Inspector.showIfYxNode,
              type: "select",
              choices: function(node, propName) {
                if (Array.isArray(node.data.choices)) return node.data.choices;
                return that.signalParamArry;
                // return [{id:1,name:'acurrent'},{id:2,name:'cvoltage'}];
              }
            }
          }
        },that);
        
      }, // end init
      TopRotatingTool() {
        go.RotatingTool.call(this);
      },
    // end of TopRotatingTool class
      
      save() {
        var structure=myDiagram.model.toJson();
        console.log(structure,'structure');
        // this.$router.push('/save')
        // if(this.companyStr==''){
        //   this.$message.warning('请选择一个企业！');
        //   return ;
        // }
        //  if(JSON.parse(structure).nodeDataArray.length==0){
        //     this.$message.warning('请绘制SVG!');
        //       return ;
        //   }
        // this.saveDiagramProperties();  // do this first, before writing to JSON
        // sysApi.setUnitStructure( { unitId:this.companyStr,token:this.token,structure: structure}).then(res => {
        //   if(res.success){
        //     this.$message.warning('操作成功！');
        //     myDiagram.model = go.Model.fromJson({});
        //     this.loadDiagramProperties();  // do this after the Model.modelData has been brought into memory
        //   }else{
        //     this.$message.warning(res.msg);
        //   }
        // });
      },
      load() {
        //  myDiagram.model = go.Model.fromJson(document.getElementById("mySavedModel").value);
        // this.loadDiagramProperties();  // do this after the Model.modelData has been brought into memory
        // if(this.companyStr==''){
        //   this.$message.warning('请选择一个企业！');
        //   return ;
        // }
        // sysApi.getUnitStructure( { unitId:this.companyStr,token:this.token}).then(res => {
          if(res.success){
            if(res.object != null && res.object != ''){
              myDiagram.model = go.Model.fromJson(JSON.parse(res.object));
              this.loadDiagramProperties();  // do this after the Model.modelData has been brought into memory
              // myDiagram.select(myDiagram.nodes.first());
              // this.getDiagramDeviceId();
              // this.getDeviceParamList();
              // this.getSignalParamList();
              //初始化inspector
		          var mynode=JSON.parse(res.object).nodeDataArray;
		          for(var i=0;i<mynode.length;i++){           
		        	  var tempNode=mynode[i];
		        	  if(tempNode.dataType=='组件' || tempNode.category=='part1'|| tempNode.category=='part2'|| tempNode.category=='part3'|| tempNode.category=='part4'|| tempNode.category=='part5'|| tempNode.category=='BYQ'|| tempNode.category=='deviceLine'){
		        		  var key=tempNode.key;
		        		  var newdat2 = myDiagram.model.findNodeDataForKey(key);
		        		  var node = myDiagram.findNodeForData(newdat2);
		        		  break ;
		        	  }
		          }
		          myDiagram.select(node);
            //   var select_dataType= document.querySelector("input[tabindex='0']");
            //   select_dataType.disabled = false;
            // var optionStr = '<option id="0">遥测</option><option id="1">遥脉</option>';
            // select_dataType.innerHTML = optionStr;

            }else{
              myDiagram.model = go.Model.fromJson({});
              this.loadDiagramProperties();  // do this after the Model.modelData has been brought into memory
              this.$message.warning('暂无图形，请添加图形！');
            }
          }else{
            this.$message.warning(res.msg);
          }
        // });
       
      },
      saveDiagramProperties() {
        myDiagram.model.modelData.position = go.Point.stringify(myDiagram.position);
      },
      loadDiagramProperties(e) {
        // set Diagram.initialPosition, not Diagram.position, to handle initialization side-effects
        var pos = myDiagram.model.modelData.position;
        if (pos) myDiagram.initialPosition = go.Point.parse(pos);
      },
      //回调方法
      nodeSelectionChanged(node) {
          if(node.isSelected) {
            //节点选中执行的内容
            var nodeData=node.data;
            var deviceId=nodeData.deviceId;
            // var deviceType=getDeviceTypeId(nodeData.deviceType);
            var dataType=nodeData.dataType;
            //设置编辑时回显参数
            var dataText=nodeData.text; 
            var deviceName=nodeData.deviceName; 
            if(dataType=='遥信'){
              var dataTypeId=3;
              console.log('遥信');
              // this.getDeviceNameByYcYm(dataTypeId,deviceName);
            }else if(dataType=='遥测'){
              var dataTypeId=0;
              console.log('遥测');
              // this.getDeviceNameByYcYm(dataTypeId,deviceName);
            }else if(dataType=='遥脉'){
              var dataTypeId=1;
              console.log('遥脉');
              // this.getDeviceNameByYcYm(dataTypeId,deviceName);
            }
            
            if(dataType=='组件'){
              // this.getDiagramDeviceId(dataText);
            }
            //选中时初始化signalParam,deviceParam下拉框
            // this.deviceParam_init(deviceId,dataTypeId,dataText);
            // this.getDiagramDeviceId(deviceId,dataTypeId)
          } 
      },
      //初始化遥信参数singnalParam和设备参数deviceParam
      deviceParam_init(deviceId,dataTypeId,dataText){
          sysApi.getDiagramParamsByCon( { deviceId:deviceId,commType:dataTypeId,token:this.token }).then(data => {
            if(data.length>0){
                var optionStr = '';
                if(dataTypeId==3){
                  this.signalParamArry=data;
                  //更改已有的select的option
                      for (var i = 0; i <this.signalParamArry.length; i++) {
                          var temp = this.signalParamArry[i];
                          optionStr += '<option >' + temp.field + '</option>';
                      }
                }else{
                  this.deviceParamArry=data;
                  //更改已有的select的option
                      for (var i = 0; i <this.deviceParamArry.length; i++) {
                          var temp = this.deviceParamArry[i];
                          optionStr += '<option >' + temp.field + '</option>';
                      }
                }
                var select2=document.querySelector("select[tabindex='2']");
                if(select2){
                  select2.innerHTML = optionStr;
                  for (var i = 0; i < select2.options.length; i++) { 
                    if (select2.options[i].text == dataText) { 
                      select2.options[i].selected = true; 
                      break; 
                    } 
                  }
                }
              }else{
                if(dataTypeId==3){
                   this.signalParamArry=[];
                }else{
                  this.deviceParamArry=[];
                }
                if(document.querySelector("select[tabindex='2']")){
                  document.querySelector("select[tabindex='2']").innerHTML = '';
                }
              }
        });
         
      },
      getDeviceNameByYcYm(dataTypeId,deviceName){  
        sysApi.getDeviceNameByYcYm( { unitId:this.companyStr,commType:dataTypeId,token:this.token }).then(data => {
            if(data.length>0){
              this.deviceNameArry=data;
            //更改已有的select的option
              var optionStr = '';
              for (var i = 0; i <this.deviceNameArry.length; i++) {
                  var temp = this.deviceNameArry[i];
                  optionStr += '<option id="' + temp.id + '">' + temp.name + '</option>';
              }
              var select2=document.querySelector("select[tabindex='1']");
              select2.innerHTML = optionStr;
              for (var i = 0; i < select2.options.length; i++) { 
                if (select2.options[i].text == deviceName) { 
                  select2.options[i].selected = true; 
                  break; 
                } 
              }
          }else{
              this.deviceNameArry=[];
              document.querySelector("select[tabindex='1']").innerHTML = '';
          }
        });
      },
      // add an SVG rendering of the diagram at the end of this page
      makeSVG() {
        let str = JSON.parse($('#mySavedModel').val())
        myDiagram.model = go.Model.fromJson(str);
        var svg = myDiagram.makeSvg({
            scale: 0.5,
            background:'black'
          });
        svg.style.border = "1px solid black";
       var obj = document.getElementById("SVGArea");
        obj.appendChild(svg);
        if (obj.children.length > 0) {
          obj.replaceChild(svg, obj.children[0]);
        }
      },
      //企业列表
      loadTree(node, resolve){
        this.$http.get(api.SYS_EQUIPMENTLOOP_GETUSERUNIT+ "?token=" + this.token).then(res => {
          this.companyStr=res.data[0].id;
          this.companyOptions=res.data;
          // this.getDiagramDeviceId();
          // this.getDeviceParamList();
          // this.getSignalParamList();
        })
      },
      //根据企业ID获取设备
      getDiagramDeviceId(dataText){
        sysApi.getDiagramDeviceId( {unitId:this.companyStr,token:this.token}).then(res => {
          if(res.length>0){
            this.deviceNameArry=res;
					 //更改已有的select的option
            var optionStr = '';
            for (var i = 0; i <this.deviceNameArry.length; i++) {
                var temp = this.deviceNameArry[i];
                optionStr += '<option id="' + temp.id + '">' + temp.name + '</option>';
            }
             var select2=document.querySelector("select[tabindex='1']");
            select2.innerHTML = optionStr;
            for (var i = 0; i < select2.options.length; i++) { 
                if (select2.options[i].text == dataText) { 
                  select2.options[i].selected = true; 
                  break; 
                } 
              }
          }else{
            this.deviceNameArry=[];
            this.$message.warning('当前企业暂无设备！');
          }
        });
      },
      
    },
    created(){
      var userInfo=JSON.parse(window.sessionStorage.getItem("user-info"));
      var myuserType=userInfo.userType;//用户类型 0是超级管理员
      this.token=userInfo.token;
      // myuserType=1
      if(myuserType==0){
        this.userType=0;
        this.loadTree();
      }else{
        this.userType=1;
        this.companyStr=userInfo.unitId;
        this.load();
      }
    },
    computed: {
      //  ...mapGetters({
      //   sidebar: 'sidebar',
      // }),
    },
    mounted() {
      this.init();
    },
    destroyed() {
      // document.removeEventListener('click', this.autoHide, false)
    },
    watch: {
      // 'sidebar.collapsed': function (val) {
      //   this.load();
      // },
    }
  }
</script>

<style lang="less" scoped>
  @import '../assets/js/DataInspector.css';
  #myPaletteDiv,#myDiagramDiv{
    background: black!important;
  }
  .svg .fa-eye{
    color: #fff;
    margin:0 5px 0 0;
  }
  .svg .fa-eye:hover{
    color: #fff;
  }
  #contextMenu {
    z-index: 10001;
    position: absolute;
    left: 5px;
    border: 1px solid #444;
    background-color: #F5F5F5;
    display: none;
    box-shadow: 0 0 10px rgba( 0, 0, 0, .4 );
    font-size: 12px;
    font-family: sans-serif;
    font-weight: bold;
  }
  #myInspectorDiv{
    width: 280px;
    position: absolute;
    z-index: 10;
    right: 10px;
    top: 10px;
   }
    #myInspectorDiv button{
      margin-left: 122px;
   }
  /*#contextMenu ul {
    list-style: none;
    top: 0;
    left: 0;
    margin: 0;
    padding: 0;
  }

  #contextMenu li a {
    position: relative;
    min-width: 60px;
    color: #444;
    display: inline-block;
    padding: 6px;
    text-decoration: none;
    cursor: pointer;
  }

  #contextMenu li:hover {
    background: #CEDFF2;
    color: #EEE;
  }

  #contextMenu li ul li {
    display: none;
  }

  #contextMenu li ul li a {
    position: relative;
    min-width: 60px;
    padding: 6px;
    text-decoration: none;
    cursor: pointer;
  }
*/
 #contextMenu ul{
      list-style:none;
    }
  #contextMenu  ul li{
      /*float: left;*/
      line-height: 40px;
      text-align: center;
      position: relative;
    }
  #contextMenu  a{
      text-decoration: none;
      color: #000;
      display: block;
      padding: 0 10px;
      height: 40px;
    }
  #contextMenu  a:hover{
      color: #fff;
      background: #666;
    }
 #contextMenu   ul li ul li{
      float: none;
      background: #eee;
      margin-top: 2px;
    }
  #contextMenu  ul li ul{
      position: absolute;
      left: 102%;
      top: -2px;
    }
   #contextMenu ul li ul li a{
      width: 120px;
    }
  #contextMenu  ul li ul li a:hover{
      background: #06f;
    }
  #contextMenu li:hover .subMenu1  {
    display: block;
  }
  #contextMenu .childLi:hover .subMenu2 {
    display: block;
  }
  #contextMenu  ul li ul{
       display: none;
    }
</style>
